﻿// =================================================================== 
// 项目说明
//====================================================================
// sushee @Copy Right 2019
// 文件： SmsCardRepository.cs
// 项目名称：斑马车务
// 创建时间：2019/9/19
// 负责人：sushee
// ===================================================================
using System;
using System.Text;
using System.Collections.Generic;
using Dapper;
using Dapper.Extensions;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;

namespace YouWei.Infrastructure.Repository
{
	/// <summary>
	///短信卡池 仓储层
	/// </summary>	
	public class SmsCardRepository:BaseRepository<SmsCard>
	{		
    
        #region 构造

        public SmsCardRepository() : base(){}

        public SmsCardRepository(string connectionString) : base(connectionString){}

        public SmsCardRepository(DatabaseContext dbContext) : base(dbContext){}

        #endregion
        /// <summary>
        /// 分页查询，带条件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public Page<SmsCardDto> GetPages(int pageIndex, long pageSize, ReqSmsCardCondition condition)
        {
            StringBuilder sql = new StringBuilder("SELECT * FROM SmsCard WITH(NOLOCK) where 1 =1");
            if (!string.IsNullOrWhiteSpace(condition.StartDate))
            {
                sql.Append(" AND CreatedTime>@StartDate");
            }
            if (!string.IsNullOrWhiteSpace(condition.EndDate))
            {
                sql.Append(" AND CreatedTime>@EndDate");
            }
            if (!string.IsNullOrWhiteSpace(condition.OwnerName))
            {
                sql.Append(" AND CHARINDEX(@OwnerName,OwnerName) >0");
            }
            if (!string.IsNullOrWhiteSpace(condition.OwnerTel))
            {
                sql.Append(" AND OwnerMobile=@OwnerMobile");
            }
            if (condition.TelType > 0)
            {
                sql.Append(" AND TelType=@TelType");
            }
            if (condition.Status > -1)
            {
                sql.Append(" AND IsDeleted=@IsDeleted");
            }
            sql.Append(" ORDER BY CreatedTime DESC");
            DynamicParameters dparams = new DynamicParameters();
            dparams.Add("@OwnerName", condition.OwnerName, System.Data.DbType.String);
            dparams.Add("@OwnerMobile", condition.OwnerTel, System.Data.DbType.String);
            dparams.Add("@StartDate", condition.StartDate, System.Data.DbType.String);
            dparams.Add("@EndDate", condition.EndDate, System.Data.DbType.String);
            dparams.Add("@TelType", condition.TelType, System.Data.DbType.Int16);
            dparams.Add("@IsDeleted", condition.Status, System.Data.DbType.Int32);
            return dbContext.Connection.Page<SmsCardDto>(pageIndex, pageSize, sql.ToString(), dparams);
        }


        public List<SmsCard> GetAvaliableCards(DateTime dtTime)
        {
            string szSql = @"SELECT 
	                            distinct c.*
                            FROM SmsCard c
                            LEFT JOIN SmsTaskCard stc
                            ON c.CardID=c.CardID
                            LEFT JOIN SmsTask t
                            ON t.TaskID=stc.TaskID
                            WHERE 
                            1=1
                            AND c.IsDeleted=0
                            AND  @dtTime>StartDate and @dtTime<EndDate and t.IsDeleted=0 and t.Status=1";
            return Query(szSql,new { dtTime = dtTime });
        }

        /// <summary>
        /// 手机号是否重复
        /// </summary>
        /// <returns></returns>
        public bool CheckMobile(string tel, int carId)
        {
            string sql = "select * from SmsCard where IsDeleted=0 and OwnerMobile=@OwnerMobile";
            if (carId > 0)
            {
                sql += " and cardid<>" + carId;
            }
            return ExecuteScalar<int>(sql, new { OwnerMobile = tel }) > 0;
        }

        /// <summary>
        /// 获取可用卡池
        /// </summary>
        /// <returns></returns>
	    public List<SmsCard> GetAvaliableCards()
	    {
	        string szSql = @"SELECT 
	                            *
                            FROM SmsCard c
                            WHERE c.IsDeleted=0";
	        return Query(szSql);
	    }

        public List<SmsCard> GetAvaliableCardsByTaskID(int taskID)
        {
            string szSql = @"SELECT 
	                            sc.*
                            FROM SmsCard sc
                            INNER JOIN SmsTaskCard st 
                            ON sc.CardID = st.CardID
                            WHERE 1=1 
                            AND st.TaskID={0} 
                            AND sc.IsDeleted=0";
            szSql = string.Format(szSql, taskID);
            return Query(szSql);
        }

        /// <summary>
        /// 批量更新短信卡状态
        /// </summary>
        /// <param name="ids">短信卡ID</param>
        /// <param name="statusType">0:启用 1:禁用</param>
        /// <returns></returns>
        public bool BulkUpdateStatus(List<int> ids,int statusType)
        {
            if (ids.Count==0)
            {
                return false;
            }
            string strIds = string.Join(",", ids.ToArray());

            string sql = "update SmsCard set IsDeleted=" + statusType + " where CardID in(" + strIds + ")";
            return Execute(sql) > 0;
        }


	    public void DisabledAllCards()
	    {
	        string szSql = @"update SmsCard set IsDeleted=1";
	        Execute(szSql);
	    }

        

    }
}